package com.example.leo.mycharmingstudent.project.util;

import com.example.leo.mycharmingstudent.a0917.practice.HandlerUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Leo on 2020/9/27.
 */

public class OkHttpUtil {

    /**
     * 为什么要封装？
     * 一个完整的应用，会调用很多接口
     * 每次请求网络接口的时候，都要写重复代码，浪费生命
     * 鉴于此，将重复代码封装成一个方法
     *
     * @param url
     * @param callback
     */
    public static void enqueue(String url, Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        //直接new Callback()，导致此处和调用处没有关联
        //也就是说，执行完网络请求以后，无法回到调用处继续执行
        /*call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });*/
        call.enqueue(callback);
    }

    public static void enqueue(String url, final MainThreadCallBack callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(final Call call, final IOException e) {
                HandlerUtil.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(call, e);
                    }
                });
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                final String result = response.body().string();
                HandlerUtil.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onResponse(call, result);
                    }
                });
            }
        });
    }


    public interface MainThreadCallBack {
        void onFailure(Call call, IOException e);

        void onResponse(Call call, String result);
    }


}
